
/*************************************************
Program: Stata_03b_make_firm_export_country_dataset.sas
Author: hannah rubinton
Date: 2/15/2019

input: export dataset
created by SAS_03_pull_trade_data.sas
and firm_2007.dta created by Stata_01_Make_firm_datasets.do 

outputs: ./work/firm_export.dta

Notes: 
************************************
****This program pulls in the export data and the firm input data to 
****construct a dataset with firm export by country

************************************
**************************************************/


**Set directories
cd ""  /* PROJECT ROOT FOLDER */
global data "data"


set more off

cap program drop clean_exports
program define clean_exports
  syntax , year(integer)

  use "$data/exports`year'_lfttd.dta", clear
	ren COUNTRY country
	ren HS hs


  *Drop mineral imports/exports
  drop if substr(hs,1,2)=="27"  // 27 is the HS2 code for minerals -- this is public data from the FTD website.
  
  *Count number of products
  gen hs10_count=1

  *Collapse to firm-country level
  collapse (sum) exp_value rp_exp_value hs10_count, by(firmid country)


  *Merge to bea country codes to collapse some of the super detailed countries
  rename country code_TD
    merge m:1 code_TD using "$data/country_data_unique.dta", keepusing(code_TD countrycode iso3)
    drop if _merge==2 
    drop _merge
    rename countrycode ctry
    drop if firmid==""
    
      
    collapse (sum) exp_value rp_exp_value, by(firmid ctry)


  *Merge to the firm data 
  merge m:1 firmid using "$data/firm_`year'.dta"

  *only keep exports that merge to our firm dataset 
  keep if _merge==3
  drop _merge 
  keep exp_value rp_exp_value firmid ctry 


  save "$data/firm_country_export`year'.dta", replace 


end //end clean_census program

*clean_exports, year(1997)
*clean_exports, year(2002)
clean_exports, year(2007)
*clean_exports, year(2012)


